import datetime
from utils.goods import get_categories
from apps.contents.models import ContentCategory
def generate_static_index_html():
    """
    生成静态的主页html文件
    """
    print('主页HTML文件生成时间\t%s' % datetime.datetime.now())

    # 1.读取主页商品数据
    # 查询商品频道和分类
    categories = get_categories()
    # 广告数据
    contents = {}
    content_categories = ContentCategory.objects.all()
    for cat in content_categories:
        contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')

    # 渲染模板的上下文
    context = {
        'categories': categories,
        'contents': contents,
    }
    # 2.读取主页html模板
    from django.template import loader
    index_html=loader.get_template('index.html')
    # 3.进行渲染
    index_data_html = index_html.render(context)
    # 4.保存到本地，实现html文件静态化
    import os
    from meiduo import settings
    file_path = os.path.join(os.path.dirname(settings.BASE_DIR), 'front_end_pc/index.html')
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(index_data_html)
